﻿namespace Grep.SharePoint.SmartDocuments
{
    using System;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using Code;
    using Lib.Extensions;
    using Microsoft.SharePoint;
    using Microsoft.SharePoint.WebPartPages;
    using WebPart=System.Web.UI.WebControls.WebParts.WebPart;

    public sealed class TemplateLibraryConnectorPageDelegate : WebControl
    {
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            bool catchException = SPSecurity.CatchAccessDeniedException;
            SPSecurity.CatchAccessDeniedException = false;
            try
            {
                ProcessWebParts();
            }
            catch
            {
                /* Catch-all to prevent *any* errors propagating to the site's head */
            }
            finally
            {
                SPSecurity.CatchAccessDeniedException = catchException;
            }
        }

        private void ProcessWebPart(WebPart wp)
        {
            if (!(wp is ListViewWebPart))
            {
                // We're only interested in the ListViewWebParts
                return;
            }

            // Install various fixes to the SharePoint javascripts
            ListViewBugFixes.FixSplitMenuJavaScriptBug(wp);

            // Install the connector
            var connector = new ListViewTemplateConnector(wp as ListViewWebPart);
            connector.SetupTemplateLibraryConnections();
        }

        private void ProcessWebParts()
        {
            WebPartManager wpManager = null;
            try
            {
                wpManager = WebPartManager.GetCurrentWebPartManager(Page);
            }
            catch
            {
                /* Fail silently */
            }

            if (wpManager != null)
            {
                wpManager.WebParts.ForEach(ProcessWebPart);
            }
        }
    }
}